from modules.filesys import FileSys
from flask import request, jsonify, send_file
import json, os

states = [False]

class MainController:
    @staticmethod
    def get_files_json():
        fileNames = FileSys.get_all_files('./resource')
        fileCount = len(fileNames)
        return jsonify({
            'fileCount': fileCount,
            'content': fileNames
        })
    
    @staticmethod
    def upload():
        if 'file' not in request.files:
            return json.dumps({
                'msg': 'No file part'
            }), 400
        file = request.files['file']
        if file.filename == '':
            return json.dumps({
                'msg': 'No selected file'
            })
        file.save(os.path.join('./resource', file.filename))
        states[0] = True
        return jsonify({
            'msg': 'Upload success'
        })
    
    @staticmethod
    def deleteFile():
        fileName = request.form.get('fileName')
        path = os.path.join('./resource', fileName)
        try:
            os.remove(path)
            states[0] = True
        except:
            pass
        return jsonify({
            'msg': 'ok'
        }), 200
    
    @staticmethod
    def download():
        fileName = request.form.get('fileName')
        path = os.path.join('./resource', fileName)
        return send_file(
            path,
            as_attachment=True,
            download_name=fileName
        )
